package com.logic.modular.gameCore.config.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;

import com.comment.pojo.domain.logic.core.CoreConfig;
import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logic.modular.gameCore.config.mapper.CoreConfigMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 全局配置(CoreConfig)表服务实现类
 *
 * @author cxy
 * @since 2024-11-18 12:06:09
 */
@Slf4j
@Service
public class CoreConfigServiceImpl extends ServiceImpl<CoreConfigMapper, CoreConfig> implements IService<CoreConfig> {
    private static final Cache<String, Map<Long, CoreConfig>> cache = Caffeine.newBuilder().build();

    @PostConstruct
    private void init() {
        CoreConfig initSelect = CoreConfig.builder().build();
        List<CoreConfig> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存战斗配置数据,数据量为:{}", list.size());
        cache.put(
                "battleConfig",
                list.stream().collect(Collectors.toMap(CoreConfig::getId, CoreConfig::init))
        );
        log.info("战斗配置数据缓存完成");
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////  基础查询

    public List<CoreConfig> listCache() {
        Map<Long, CoreConfig> values = cache.getIfPresent("battleConfig");
        if (Objects.isNull(values)) {
            throw new RuntimeException("战斗配置数据为空");
        }
        return new ArrayList<>(values.values());
    }

    public Map<Long, CoreConfig> mapCache() {
        Map<Long, CoreConfig> values = cache.getIfPresent("battleConfig");
        if (Objects.isNull(values)) {
            throw new RuntimeException("战斗配置数据为空");
        }
        return values;
    }

    public static CoreConfig getCache(Long id) {
        Map<Long, CoreConfig> values = cache.getIfPresent("battleConfig");
        if (Objects.isNull(values)) {
            throw new RuntimeException("战斗配置数据为空");
        }
        return values.get(id);
    }

    public CoreConfig select(Long id) {
        CoreConfig battleConfig = getCache(id);
        if (battleConfig == null) {
            battleConfig = getById(id);
        }
        return battleConfig;
    }
}
